package com.tpshion.cloud.core.interceptor;

import com.tpshion.cloud.common.support.AuthInfo;
import com.tpshion.cloud.common.support.Constants;
import com.tpshion.cloud.common.support.Field;
import com.tpshion.cloud.common.utils.JsonUtil;
import com.tpshion.cloud.common.utils.JwtUtil;
import com.tpshion.cloud.core.annotation.SessionAware;
import com.tpshion.cloud.core.support.Session;
import com.tpshion.cloud.core.support.SessionHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * 从request中获取session相关信息进行封装
 */
@Component
public class SessionInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(SessionInterceptor.class);

    @Value("${spring.application.name:unknow}")
    private String systemCode;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
            for (MethodParameter methodParameter : methodParameters) {
                if (methodParameter.hasParameterAnnotation(SessionAware.class)){
                    Session session = new Session();
                    session.setTraceId((String) request.getAttribute(Field.TRACE_ID));
                    session.setSystemCode(systemCode);
                    if(null != request.getHeader(Field.TOKEN)){
                        AuthInfo authInfo = JwtUtil.getUserInfo(request.getHeader(Field.TOKEN));
                        log.info("*** SessionInterceptor authInfo:{}",authInfo);
                        BeanUtils.copyProperties(authInfo,session);
                    }
                    SessionHolder.set(session);
                    log.info("request session={}",session);
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SessionHolder.remove();
    }
}
